//
//  NvEditFilterViewController.m
//  SDKDemo
//
//  Created by ms20180425 on 2018/6/12.
//  Copyright © 2018年 meishe. All rights reserved.
//

#import "NvEditFilterViewController.h"
#import "NvLiveWindowPanelView.h"
#import "NvAssetManager.h"
#import "NvEditFilterItem.h"
#import "NvFilterCollectionViewCell.h"
#import "NvsTimelineVideoFx.h"
#import "NvMoreDownloadViewController.h"
#import "NvAsset.h"
#import "NvTimelineFilterUtils.h"
#import "NvTimelineData.h"
#import "NvTimelineUtils.h"
#import "NvFilterStrength.h"
#import "NvMoreFilterViewController.h"
#import "NvSDKUtils.h"

@interface NvEditFilterViewController ()<UICollectionViewDelegate, UICollectionViewDataSource,NvAssetManagerDelegate>

@property (nonatomic, strong) NvLiveWindowPanelView *liveWindowPanel;
@property (nonatomic, strong) NvsStreamingContext *streamingContext;

@property (nonatomic, strong) UIView *filterPanelView;
@property (nonatomic, strong) UICollectionView *filterCollectionView;
@property (nonatomic, strong) NSMutableArray<NvEditFilterItem *> *filterDataSource;

@property (nonatomic, strong) NvAssetManager *assetManager;
@property (nonatomic, strong) NvFilterStrength *filterStrength;
@property (nonatomic, strong) NSString *currentThemeId;
@property(strong, nonatomic) NvThemeInfoModel *themeInfo;
@property (nonatomic, strong) NvsTimelineVideoFx *currentFx;

@property (nonatomic, strong)UIView *line;

@end

@implementation NvEditFilterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.streamingContext = [NvsStreamingContext sharedInstance];
    self.title = @"滤镜";
    [self addSubViews];
    [self initTimeline];
    [_liveWindowPanel connectTimeline:_timeline];
    [self.liveWindowPanel hiddenVolumeButton];
    [self seekTimeline:0];
    // Do any additional setup after loading the view.
    
    self.assetManager = [NvAssetManager sharedInstance];
    self.assetManager.delegate = self;
    [self.assetManager searchLocalAssets:ASSET_FILTER];
    NSString *itemPath = [[[NSBundle bundleForClass:[self class]] bundlePath] stringByAppendingPathComponent:@"filter"];
    [self.assetManager searchReservedAssets:ASSET_FILTER bundlePath:itemPath];
    [self getDefaultData];
    [self.filterCollectionView reloadData];
    self.currentThemeId = [self.timeline getCurrentThemeId];
    [self.timeline removeCurrentTheme];
    self.themeInfo = [[[NvTimelineData sharedInstance] themeInfo] copy];
    [[NvTimelineData sharedInstance] setThemeInfo:[NvThemeInfoModel new]];
    NvTimeFilterInfoModel *model = [[NvTimelineData sharedInstance] videoFxDataArray].firstObject;
    if (model && ![model.name isEqualToString:@"无"] && model.name!=nil) {
        self.filterStrength.hidden = NO;
        [self.filterStrength setFilterStrengthValue:model.strength];
    }
}

- (void)initReservedAssetName:(NvAsset *)asset {
    if ([asset isReserved]) {
        if ([asset.uuid isEqualToString:@"0FBCC8A1-C16E-4FEB-BBDE-D04B91D98A40"]) {
            asset.name = @"白皙";
        }
        if ([asset.uuid isEqualToString:@"6439CF7E-42D5-4239-8187-358323292FF4"]) {
            asset.name = @"冰激凌";
        }
        if ([asset.uuid isEqualToString:@"FAE50247-F14C-40CE-AD43-29CA3E604838"]) {
            asset.name = @"晨曦";
        }
        if ([asset.uuid isEqualToString:@"BD9D5DA9-581E-4B80-95D4-218D95FC78F2"]) {
            asset.name = @"风语";
        }
        if ([asset.uuid isEqualToString:@"394EB525-1B7A-4AA1-BBAD-3FD75527A60C"]) {
            asset.name = @"过往";
        }
        if ([asset.uuid isEqualToString:@"12FCD2E7-1F80-4DFC-A8FD-C820CF754855"]) {
            asset.name = @"雷耶斯";
        }
        if ([asset.uuid isEqualToString:@"D65436B7-D19F-47E0-9A2A-28CECC73D4F2"]) {
            asset.name = @"蜜桃";
        }
        if ([asset.uuid isEqualToString:@"B7F1F498-B310-4E2D-9A75-7D8AFBBC71D8"]) {
            asset.name = @"切尔西";
        }
        if ([asset.uuid isEqualToString:@"C9CE10F1-7C77-423C-BB7F-7F090C33D5C5"]) {
            asset.name = @"青春";
        }
        if ([asset.uuid isEqualToString:@"F7204261-41D8-454A-99DC-3522444739EB"]) {
            asset.name = @"斋普尔";
        }
        if ([asset.uuid isEqualToString:@"E1202F90-F2C8-4A14-BFCB-8F62BBD72F56"]) {
            asset.name = @"筑地";
        }
    }
}

- (UIView *)leftNavigationBarItemView {
    return [UIView new];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self connectLiveWindow];
    [self getDefaultData];
    [self.filterCollectionView reloadData];
}

- (void)initTimeline {
    self.timeline = [NvTimelineUtils createTimeline:self.editMode];
    [NvTimelineUtils recreateTimeline:self.timeline];
}

- (void)dealloc {
    
}
// 获取默认数据
- (void)getDefaultData {
    self.filterDataSource = [NSMutableArray array];
    NvsTimelineVideoFx *filterFx = [self.timeline getLastTimelineVideoFx];
    AspectRatio ratio;
    switch (self.editMode) {
        case NvEditMode16v9:
            ratio = AspectRatio_16v9;
            break;
        case NvEditMode1v1:
            ratio = AspectRatio_1v1;
            break;
        case NvEditMode9v16:
            ratio = AspectRatio_9v16;
            break;
        case NvEditMode3v4:
            ratio = AspectRatio_3v4;
            break;
        case NvEditMode4v3:
            ratio = AspectRatio_4v3;
            break;
        default:
            ratio = AspectRatio_All;
            break;
    }
    NvTimeFilterInfoModel *model = [[NvTimelineData sharedInstance] videoFxDataArray].firstObject;
    NSArray *cartoonArray = @[@"NvCaptureCartoon1",@"NvCaptureCartoon2",@"NvCaptureCartoon3"];
    for (int i = 0; i<3; i++) {
        NvEditFilterItem *itemCartoon = [NvEditFilterItem new];
        itemCartoon.imageUrl = [cartoonArray[i] stringByAppendingString:@".jpg"];
        itemCartoon.packageId = @"Cartoon";
        if (i == 0) {
            itemCartoon.name = @"漫画书";
            itemCartoon.strokeOnly = NO;
            itemCartoon.grayscale = NO;
        }else if (i == 1){
            itemCartoon.name = @"水墨";
            itemCartoon.strokeOnly = YES;
            itemCartoon.grayscale = NO;
        }else if (i == 2){
            itemCartoon.name = @"单色漫画";
            itemCartoon.strokeOnly = NO;
            itemCartoon.grayscale = YES;
        }
        if ([itemCartoon.packageId isEqualToString:model.name]) {
            if (itemCartoon.grayscale == model.grayscale && itemCartoon.strokeOnly == model.strokeOnly) {
                itemCartoon.isSelect = YES;
            }
        }else{
            itemCartoon.isSelect = NO;
        }
        [self.filterDataSource addObject:itemCartoon];
    }
    
    NSArray *array = [self.assetManager getUsableAssets:ASSET_FILTER aspectRatio:ratio categoryId:NV_CATEGORY_ID_ALL];
    for (NvAsset *asset in array) {
        if ([asset isReserved]) {
            NvEditFilterItem *item = [NvEditFilterItem new];
            item.imageUrl = [asset.coverUrl absoluteString];
            [self initReservedAssetName:asset];
            item.name = asset.name;
            item.packageId = asset.uuid;
            if ([item.packageId isEqualToString:filterFx.timelineVideoFxPackageId]) {
                item.isSelect = YES;
            } else {
                item.isSelect = NO;
            }
            [_filterDataSource insertObject:item atIndex:3];
        }
    }
    for (NvAsset *asset in array) {
        if (![asset isReserved]) {
            NvEditFilterItem *item = [NvEditFilterItem new];
            item.imageUrl = [asset.coverUrl absoluteString];
            item.name = asset.name;
            item.packageId = asset.uuid;
            if ([item.packageId isEqualToString:filterFx.timelineVideoFxPackageId]) {
                item.isSelect = YES;
            } else {
                item.isSelect = NO;
            }
            [_filterDataSource insertObject:item atIndex:0];
        }
    }
//    NSArray *videoFxArray = [NSArray arrayWithObjects:@"Sage", @"Maid", @"Mace", @"Lace", @"Mall", @"Sap", @"Sara", @"Pinky", @"Sweet", @"Fresh", nil];
//    NSArray *videoFxDisplayArray = [NSArray arrayWithObjects:@"明快", @"少女时代", @"锐利", @"蕾丝", @"时尚", @"元气", @"调皮", @"草莓薄荷", @"粉嫩", @"清爽", nil];
//    for (int i = 0; i < videoFxArray.count; i++) {
//        NvEditFilterItem *item = [NvEditFilterItem new];
//        item.packageId = videoFxArray[i];
//        item.imageUrl = [NvUtils getFilterCoverName:videoFxArray[i]];
//        item.name = videoFxArray[i];
//        if ([item.name isEqualToString:filterFx.bultinTimelineVideoFxName]) {
//            item.isSelect = YES;
//        } else {
//            item.isSelect = NO;
//        }
//        [self.filterDataSource addObject:item];
//    }
    
    NvEditFilterItem *item = [NvEditFilterItem new];
    item.imageUrl = @"NvsFilterNone";
    item.name = @"无";
    item.packageId = nil;
    item.isSelect = NO;
    if (filterFx.bultinTimelineVideoFxName == nil) {
        if (!filterFx.timelineVideoFxPackageId || [filterFx.timelineVideoFxPackageId isEqualToString:@""]) {
            item.isSelect = YES;
        } else {
            item.isSelect = NO;
        }
    }
    
    [self.filterDataSource insertObject:item atIndex:0];
    
}


- (void)connectLiveWindow {
    [_liveWindowPanel connectTimeline:_timeline];
    [self seekTimeline:_liveWindowPanel.currentTime];
}

- (void)addSubViews{
    if (KIsiPhoneX) {
            self.filterPanelView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGTH - 137*SCREANSCALE - 34 - NV_STATUSBARHEIGHT - NV_NAV_BAR_HEIGHT, SCREEN_WDITH, 137*SCREANSCALE + 34)];
    }else{
            self.filterPanelView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGTH - 137*SCREANSCALE - 34 - NV_STATUSBARHEIGHT, SCREEN_WDITH, 137*SCREANSCALE + 34)];
    }
    self.liveWindowPanel = [[NvLiveWindowPanelView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.width)];
    _liveWindowPanel.editMode = self.editMode;
    [self.view addSubview:_liveWindowPanel];
    //    _themePanelView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:self.filterPanelView];
    
    UIButton *moreB = [UIButton buttonWithType:UIButtonTypeCustom];
    moreB.tag = 1101;
    [moreB setImage:[NvUtils imageWithName:@"NvsFilterMore"] forState:UIControlStateNormal];
    moreB.frame = CGRectMake(13 * SCREANSCALE, 23 * SCREANSCALE, 35 * SCREANSCALE, 25 * SCREANSCALE);
    [self.filterPanelView addSubview:moreB];
    [moreB addTarget:self action:@selector(moreClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *moreL = [[UILabel alloc]initWithFrame:CGRectMake(20 * SCREANSCALE, moreB.frame.origin.y + moreB.frame.size.height + 15, 30 * SCREANSCALE, 21 * SCREANSCALE)];
    moreL.text = @"更多";
    moreL.textColor = [UIColor nv_colorWithHexARGB:@"#CCFFFFFF"];
    moreL.font = [NvUtils regularFontWithSize:11];
    [self.filterPanelView addSubview:moreL];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(49*SCREANSCALE, 70*SCREANSCALE);
    layout.minimumLineSpacing = 10*SCREANSCALE;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 16*SCREANSCALE, 0, 0);
    self.filterCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(60 * SCREANSCALE, 0, SCREEN_WDITH - 60 * SCREANSCALE, 85*SCREANSCALE) collectionViewLayout:layout];
    self.filterCollectionView.delegate = self;
    self.filterCollectionView.dataSource = self;
    self.filterCollectionView.backgroundColor = UIColorFromRGB(0x242728);
    self.filterCollectionView.showsHorizontalScrollIndicator = NO;
    [self.filterPanelView addSubview:self.filterCollectionView];
    [self.filterCollectionView registerClass:[NvFilterCollectionViewCell class] forCellWithReuseIdentifier:@"NvFilterCollectionViewCell"];
    
    UIButton *finshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [finshBtn setImage:[NvUtils imageWithName:@"Nvcheck - material"] forState:UIControlStateNormal];
    finshBtn.frame = CGRectMake(175 * SCREANSCALE, 102 *SCREANSCALE, 25 * SCREANSCALE, 20 * SCREANSCALE);
    [finshBtn addTarget:self action:@selector(finshClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.filterPanelView addSubview:finshBtn];
    
    self.line = [[UIView alloc] initWithFrame:CGRectMake(0, finshBtn.top - 16*SCREANSCALE, SCREANWIDTH, 0.5)];
    self.line.backgroundColor = [UIColor nv_colorWithHexARGB:@"#1AFFFFFF"];
    [self.view addSubview:self.line];
    
    self.filterStrength = [[NvFilterStrength alloc] initWithFrame:CGRectMake(0, self.liveWindowPanel.bottom, SCREANWIDTH, 63*SCREANSCALE)];
    self.filterStrength.delegate = self;
    [self.view addSubview:self.filterStrength];
    self.filterStrength.hidden = YES;
}

- (void)finshClick:(UIButton *)button {
    [[NvTimelineData sharedInstance] setThemeInfo:self.themeInfo];
    
    [self.streamingContext removeTimeline:self.timeline];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)moreClick:(UIButton *)button {
//    NvMoreDownloadViewController *moreDownload = [NvMoreDownloadViewController new];
//    moreDownload.type = ASSET_FILTER;
//    [self.navigationController pushViewController:moreDownload animated:YES];
    NvMoreFilterViewController *vc = [[NvMoreFilterViewController alloc]init];
    vc.editModel = self.editMode;
    vc.type = ASSET_FILTER;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)applyFilter:(NvEditFilterItem *)item {
    for (NvTimeFilterInfoModel *info in [[NvTimelineData sharedInstance] videoFxDataArray]) {
        if (!info.isDouyin) {
            info.name = item.packageId;
            info.grayscale = item.grayscale;
            info.strokeOnly = item.strokeOnly;
            info.strength = 1;
            if (self.currentFx) {
                [self.timeline removeTimelineVideoFx:self.currentFx];
            }
            if ([NvSDKUtils isBuiltinFilter:info.name]) {
                self.currentFx = [self.timeline addBuiltinTimelineVideoFx:0 duration:self.timeline.duration videoFxName:info.name];
                if ([info.name isEqualToString:@"Cartoon"]) {
                    [self.currentFx setBooleanVal:@"Stroke Only" val:item.strokeOnly];
                    [self.currentFx setBooleanVal:@"Grayscale" val:item.grayscale];
                }
                [self.currentFx setFilterIntensity:info.strength];
            } else {
                self.currentFx = [self.timeline addPackagedTimelineVideoFx:0 duration:self.timeline.duration videoFxPackageId:info.name];
                [self.currentFx setFilterIntensity:info.strength];
            }

            if (self.streamingContext.getStreamingEngineState != NvsStreamingEngineState_Playback) {
                [self.liveWindowPanel playBackStart:[self.streamingContext getTimelineCurrentPosition:self.timeline] end:_timeline.duration];
            }
            
            return;
        }
    }

    NvTimeFilterInfoModel *info = NvTimeFilterInfoModel.new;
    info.inPoint = 0;
    info.outPoint = self.timeline.duration;
    info.name = item.packageId;
    info.strength = 1;
    info.grayscale = item.grayscale;
    info.strokeOnly = item.strokeOnly;
    [[[NvTimelineData sharedInstance] videoFxDataArray] addObject:info];
    
    if (self.currentFx) {
        [self.timeline removeTimelineVideoFx:self.currentFx];
    }
    if ([NvSDKUtils isBuiltinFilter:info.name]) {
        self.currentFx = [self.timeline addBuiltinTimelineVideoFx:0 duration:self.timeline.duration videoFxName:info.name];
        if ([info.name isEqualToString:@"Cartoon"]) {
            [self.currentFx setBooleanVal:@"Stroke Only" val:item.strokeOnly];
            [self.currentFx setBooleanVal:@"Grayscale" val:item.grayscale];
        }
        [self.currentFx setFilterIntensity:info.strength];
    } else {
        self.currentFx = [self.timeline addPackagedTimelineVideoFx:0 duration:self.timeline.duration videoFxPackageId:info.name];
        [self.currentFx setFilterIntensity:info.strength];
    }
    
    if (self.streamingContext.getStreamingEngineState != NvsStreamingEngineState_Playback) {
        [self.liveWindowPanel playBackStart:[self.streamingContext getTimelineCurrentPosition:self.timeline] end:_timeline.duration];
    }
    
//    [NvTimelineUtils resetVideoFx:self.timeline videoFxDataArray:[[NvTimelineData sharedInstance] videoFxDataArray]];
//    [self.liveWindowPanel playAtTime:0];
    return;
}

// 定位某一时间戳的图像
- (void)seekTimeline:(int64_t)postion {
    if (![_streamingContext seekTimeline:_timeline timestamp:postion videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:NvsStreamingEngineSeekFlag_ShowCaptionPoster | NvsStreamingEngineSeekFlag_ShowAnimatedStickerPoster])
        NSLog(@"定位时间线失败！");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.filterDataSource.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NvFilterCollectionViewCell *cell = [self.filterCollectionView dequeueReusableCellWithReuseIdentifier:@"NvFilterCollectionViewCell" forIndexPath:indexPath];
    [cell renderCellWithItem:self.filterDataSource[indexPath.row]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    for (NvEditFilterItem *item in self.filterDataSource) {
        item.isSelect = NO;
    }
    NvEditFilterItem *item = self.filterDataSource[indexPath.row];
    item.isSelect = YES;
    [self.filterCollectionView reloadData];
    [self applyFilter:item];
    
    if (indexPath.item == 0) {
        self.filterStrength.hidden = YES;
    } else {
            self.filterStrength.hidden = NO;
            NvsTimelineVideoFx *videoFx = [_timeline getFirstTimelineVideoFx];
            [self.filterStrength setFilterStrengthValue:[videoFx getFilterIntensity]];
            NSLog(@"%f",[videoFx getFilterIntensity]);
    }
}

#pragma mark NvFilterStrengthDelegate
- (void)filterStrengthValueChange:(float)value {
    NvsTimelineVideoFx *videoFx = [_timeline getFirstTimelineVideoFx];
    [videoFx setFilterIntensity:value];
    
    if ([self.streamingContext getStreamingEngineState]!=NvsStreamingEngineState_Playback) {
        [self seekTimeline:[self.streamingContext getTimelineCurrentPosition:self.timeline]];
    }
    
    for (NvTimeFilterInfoModel *info in [[NvTimelineData sharedInstance] videoFxDataArray]) {
        info.strength = value;
    }
    
}

@end
